package cn.itcast.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author 虎哥
 */
@Component
public class LoginFilter extends ZuulFilter{
    /**
     * 过滤器类型
     * @return 过滤器类型
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 过滤器的顺序
     */
    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 是否参与过滤
     * @return true，参与过滤，执行run方法。false，不参与，不执行run方法
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤的业务
     */
    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 取出 access-token
        String token = request.getParameter("access-token");
        // 判断值是否为admin
        if(!"admin".equalsIgnoreCase(token)){
            // 不是，则拦截
            ctx.setSendZuulResponse(false);
            // 禁止访问
            ctx.setResponseStatusCode(403);
        }
        // 如果是，放行
        return null;
    }
}
